

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  
    <meta name="baidu-site-verification" content="jre71SFl7b" />
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="lixinsta">
  <meta name="keywords" content="">
  <title>JS DOM操作——事件 - 自学前端的程序猿</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="自学前端的程序猿" type="application/atom+xml">
</head>


<body>
  <header style="height: 40vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>自学前端的程序猿</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-images"></i>
                思维导图
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.processon.com/view/5f3944647d9c0806d41a7d7a#map">
                    
                    HTML
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.processon.com/view/5f3a1982079129531b5ec238#map">
                    
                    CSS
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    JavaScript
                  </a>
                
              </div>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-08-19 21:50" pubdate>
      2020年8月19日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      54
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">JS DOM操作——事件</h1>
            
            <div class="markdown-body" id="post-body">
              <h1 id="事件基础"><a href="#事件基础" class="headerlink" title="事件基础"></a>事件基础</h1><h2 id="事件概述"><a href="#事件概述" class="headerlink" title="事件概述"></a>事件概述</h2><p>JavaScript 使我们有能力创建动态页面，而事件是可以被 JavaScript 侦测到的行为。</p>
<p>简单理解： <strong>触发— 响应机制</strong>。</p>
<p>​    网页中的每个元素都可以产生某些可以触发 JavaScript 的事件，例如，我们可以在用户点击某按钮时产生一个 事件，然后去执行某些操作。</p>
<h2 id="事件三要素"><a href="#事件三要素" class="headerlink" title="事件三要素"></a>事件三要素</h2><ul>
<li>事件源（谁）：触发事件的元素</li>
<li>事件类型（什么事件）： 例如 click 点击事件</li>
<li>事件处理程序（做啥）：事件触发后要执行的代码(函数形式)，事件处理函数</li>
</ul>
<p><strong>案例代码</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;body&gt;
    &lt;button id=<span class="hljs-string">&quot;btn&quot;</span>&gt;唐伯虎&lt;/button&gt;
    &lt;script&gt;
        <span class="hljs-comment">// 点击一个按钮，弹出对话框</span>
        <span class="hljs-comment">// 1. 事件是有三部分组成  事件源  事件类型  事件处理程序   我们也称为事件三要素</span>
        <span class="hljs-comment">//(1) 事件源 事件被触发的对象   谁  按钮</span>
        <span class="hljs-keyword">var</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&#x27;btn&#x27;</span>);
        <span class="hljs-comment">//(2) 事件类型  如何触发 什么事件 比如鼠标点击(onclick) 还是鼠标经过 还是键盘按下</span>
        <span class="hljs-comment">//(3) 事件处理程序  通过一个函数赋值的方式 完成</span>
        btn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
            alert(<span class="hljs-string">&#x27;点秋香&#x27;</span>);
        &#125;
    &lt;/script&gt;
&lt;/body&gt;</code></pre></div>

<h2 id="执行事件的步骤"><a href="#执行事件的步骤" class="headerlink" title="执行事件的步骤"></a>执行事件的步骤</h2><ol>
<li>获取事件源</li>
<li>注册事件（绑定事件）</li>
<li>添加事件处理程序（采用函数赋值形式）</li>
</ol>
<p><strong>案例代码</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;body&gt;
    &lt;div&gt;<span class="hljs-number">123</span>&lt;/div&gt;
    &lt;script&gt;
        <span class="hljs-comment">// 执行事件步骤</span>
        <span class="hljs-comment">// 点击div 控制台输出 我被选中了</span>
        <span class="hljs-comment">// 1. 获取事件源</span>
        <span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;div&#x27;</span>);
        <span class="hljs-comment">// 2.绑定事件 注册事件</span>
        <span class="hljs-comment">// div.onclick </span>
        <span class="hljs-comment">// 3.添加事件处理程序 </span>
        div.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我被选中了&#x27;</span>);
        &#125;
    &lt;/script&gt;
&lt;/body&gt;</code></pre></div>

<h2 id="常见的鼠标事件"><a href="#常见的鼠标事件" class="headerlink" title="常见的鼠标事件"></a>常见的鼠标事件</h2><table>
<thead>
<tr>
<th>鼠标事件</th>
<th>触发条件</th>
</tr>
</thead>
<tbody><tr>
<td>onclick</td>
<td>鼠标点击左键触发</td>
</tr>
<tr>
<td>onmouseover</td>
<td>鼠标经过触发</td>
</tr>
<tr>
<td>onmouseout</td>
<td>鼠标离开触发</td>
</tr>
<tr>
<td>onfocus</td>
<td>获得鼠标焦点触发</td>
</tr>
<tr>
<td>onblur</td>
<td>失去鼠标焦点触发</td>
</tr>
<tr>
<td>onmousemove</td>
<td>鼠标移动触发</td>
</tr>
<tr>
<td>onmouseup</td>
<td>鼠标弹起触发</td>
</tr>
<tr>
<td>onmousedown</td>
<td>鼠标按下触发</td>
</tr>
</tbody></table>
<h2 id="常用的键盘事件"><a href="#常用的键盘事件" class="headerlink" title="常用的键盘事件"></a>常用的键盘事件</h2><table>
<thead>
<tr>
<th>键盘事件</th>
<th>触发条件</th>
</tr>
</thead>
<tbody><tr>
<td>onkeyup</td>
<td>某个键盘按键被松开时触发</td>
</tr>
<tr>
<td>onkeydown</td>
<td>某个键盘按键被按下时触发</td>
</tr>
<tr>
<td>onkeypress</td>
<td>某个键盘按键被按下时触发，不识别功能键，如：ctrl、shift、 箭头等</td>
</tr>
</tbody></table>
<p><strong>注意：</strong></p>
<ol>
<li>如果使用addEventListener 不需要加 on</li>
<li>onkeypress 和前面2个的区别是：它不识别功能键</li>
<li>三个事件执行顺序：keydown–&gt;keypress–&gt;keyup</li>
</ol>
<div class="hljs"><pre><code class="hljs javascript">&lt;script&gt;
        <span class="hljs-comment">// 常用的键盘事件</span>
        <span class="hljs-comment">//1. keyup 按键弹起的时候触发 </span>
        <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;keyup&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我弹起了&#x27;</span>);
        &#125;)

        <span class="hljs-comment">//3. keypress 按键按下的时候触发  不能识别功能键 比如 ctrl shift 左右箭头啊</span>
        <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;keypress&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我按下了press&#x27;</span>);
        &#125;)
        <span class="hljs-comment">//2. keydown 按键按下的时候触发  能识别功能键 比如 ctrl shift 左右箭头啊</span>
        <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;keydown&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我按下了down&#x27;</span>);
        &#125;)
        <span class="hljs-comment">// 4. 三个事件的执行顺序  keydown -- keypress -- keyup</span>
&lt;/script&gt;</code></pre></div>

<h3 id="键盘事件对象"><a href="#键盘事件对象" class="headerlink" title="键盘事件对象"></a>键盘事件对象</h3><table>
<thead>
<tr>
<th>键盘事件对象属性</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>keyCode</td>
<td>返回该键的 ASCII 值</td>
</tr>
</tbody></table>
<p><strong>注意：</strong></p>
<ol>
<li>onkeydown 和 onkeyup 不区分大小写，onkeypress区分字母大小写</li>
<li>更多的使用 keydown 和 keyup ，它能识别所有的键（包括功能键）</li>
<li>keypress不识别功能键，但是 keyCode 属性能区分大小写，返回不同的 ASCII 值</li>
</ol>
<p><strong>使用keyCode属性判断用户按下哪个键</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;script&gt;
    <span class="hljs-comment">// 键盘事件对象中的keyCode属性可以得到相应键的ASCII码值</span>
    <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;keyup&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;up:&#x27;</span> + e.keyCode);
        <span class="hljs-comment">// 我们可以利用keycode返回的ASCII码值来判断用户按下了那个键</span>
        <span class="hljs-keyword">if</span> (e.keyCode === <span class="hljs-number">65</span>) &#123;
            alert(<span class="hljs-string">&#x27;您按下的a键&#x27;</span>);
        &#125; <span class="hljs-keyword">else</span> &#123;
            alert(<span class="hljs-string">&#x27;您没有按下a键&#x27;</span>)
        &#125;
    &#125;)
    <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;keypress&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
        <span class="hljs-comment">// console.log(e);</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;press:&#x27;</span> + e.keyCode);
    &#125;)
&lt;/script&gt;</code></pre></div>

<h1 id="事件高级"><a href="#事件高级" class="headerlink" title="事件高级"></a>事件高级</h1><h2 id="注册事件（2种方式）"><a href="#注册事件（2种方式）" class="headerlink" title="注册事件（2种方式）"></a>注册事件（2种方式）</h2><p><img src="./1551165252019.png" srcset="/img/loading.gif" alt="1551165252019"></p>
<h2 id="事件监听"><a href="#事件监听" class="headerlink" title="事件监听"></a>事件监听</h2><h4 id="addEventListener-事件监听（IE9以后支持）"><a href="#addEventListener-事件监听（IE9以后支持）" class="headerlink" title="addEventListener()事件监听（IE9以后支持）"></a>addEventListener()事件监听（IE9以后支持）</h4><blockquote>
<p>eventTarget.addEventListener(type, listener[,useCapture])</p>
<p>type：事件类型字符串，如 click、mouseover，注意不带 on</p>
<p>listener：事件处理函数，事件发生时，会调用该监听函数</p>
<p>useCapture：可选参数，是一个布尔值。默认 false。</p>
</blockquote>
<p>eventTarget.addEventListener()方法将指定的监听器注册到 eventTarget（目标对象）上，当该对象触发指定的事件时，就会执行事件处理函数。</p>
<h4 id="attacheEvent-事件监听（IE678支持）"><a href="#attacheEvent-事件监听（IE678支持）" class="headerlink" title="attacheEvent()事件监听（IE678支持）"></a>attacheEvent()事件监听（IE678支持）</h4><blockquote>
<p>eventTarget.attachEvent(eventNameWithOn,callback)</p>
<p>eventNameWithOn：事件类型字符串，比如 onclick、onmouseover，这里需要带 on</p>
<p>callback：事件处理函数，当目标触发事件时回调函数被调用</p>
</blockquote>
<p>​    eventTarget.attachEvent()方法将指定的监听器注册到 eventTarget（目标对象） 上，当该对象触发指定的事件时，指定的回调函数就会被执行。</p>
<div class="hljs"><pre><code class="hljs js">&lt;button&gt;传统注册事件&lt;/button&gt;
&lt;button&gt;方法监听注册事件&lt;/button&gt;
&lt;button&gt;ie9 attachEvent&lt;/button&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> btns = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">&#x27;button&#x27;</span>);
    <span class="hljs-comment">// 1. 传统方式注册事件</span>
    btns[<span class="hljs-number">0</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-string">&#x27;hi&#x27;</span>);
    &#125;
    btns[<span class="hljs-number">0</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
            alert(<span class="hljs-string">&#x27;hao a u&#x27;</span>);
        &#125;
   <span class="hljs-comment">// 2. 事件侦听注册事件 addEventListener </span>
   <span class="hljs-comment">// (1) 里面的事件类型是字符串 必定加引号 而且不带on</span>
   <span class="hljs-comment">// (2) 同一个元素 同一个事件可以添加多个侦听器（事件处理程序）</span>
    btns[<span class="hljs-number">1</span>].addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-number">22</span>);
    &#125;)
    btns[<span class="hljs-number">1</span>].addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
            alert(<span class="hljs-number">33</span>);
    &#125;)
    <span class="hljs-comment">// 3. attachEvent ie9以前的版本支持</span>
    btns[<span class="hljs-number">2</span>].attachEvent(<span class="hljs-string">&#x27;onclick&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-number">11</span>);
    &#125;)
&lt;/script&gt;</code></pre></div>

<h4 id="事件监听兼容性解决方案"><a href="#事件监听兼容性解决方案" class="headerlink" title="事件监听兼容性解决方案"></a>事件监听兼容性解决方案</h4><p>封装一个函数，函数中判断浏览器的类型：</p>
<div class="hljs"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addEventListener</span>(<span class="hljs-params">element,eventName, fn</span>)</span>&#123;
    <span class="hljs-comment">// 判断当前浏览器是否支持 addEventListener 方法</span>
    <span class="hljs-keyword">if</span> (element.addEventListener) &#123;
        element.addEventListener(eventName, fn);
    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (element.attacheEvent) &#123;
        element.attacheEvent(<span class="hljs-string">&#x27;on&#x27;</span> + eventName, fn);
    &#125; <span class="hljs-keyword">else</span> &#123;
        <span class="hljs-comment">// 相当于 element.onclick = fn;</span>
        element[<span class="hljs-string">&#x27;on&#x27;</span> + eventName] = fn;
    &#125; 
&#125;</code></pre></div>

<h2 id="删除事件（解绑事件）"><a href="#删除事件（解绑事件）" class="headerlink" title="删除事件（解绑事件）"></a>删除事件（解绑事件）</h2><blockquote>
<p>1、传统注册方式</p>
<p>eventTarget.onclick = null;</p>
<p>2、方法监听注册方式</p>
<ol>
<li>eventTarget.removerEventListener(type,listener[,useCapture]);</li>
<li>eventTarget.datachEvent(eventNameWithon,callback);</li>
</ol>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;div&gt;<span class="hljs-number">1</span>&lt;/div&gt;
&lt;div&gt;<span class="hljs-number">2</span>&lt;/div&gt;
&lt;div&gt;<span class="hljs-number">3</span>&lt;/div&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> divs = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">&#x27;div&#x27;</span>);
    divs[<span class="hljs-number">0</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-number">11</span>);
        <span class="hljs-comment">// 1. 传统方式删除事件</span>
        divs[<span class="hljs-number">0</span>].onclick = <span class="hljs-literal">null</span>;
    &#125;
    <span class="hljs-comment">// 2. removeEventListener 删除事件</span>
    divs[<span class="hljs-number">1</span>].addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, fn) <span class="hljs-comment">// 里面的fn 不需要调用加小括号</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-number">22</span>);
        divs[<span class="hljs-number">1</span>].removeEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, fn);
    &#125;
    <span class="hljs-comment">// 3. detachEvent</span>
    divs[<span class="hljs-number">2</span>].attachEvent(<span class="hljs-string">&#x27;onclick&#x27;</span>, fn1);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn1</span>(<span class="hljs-params"></span>) </span>&#123;
        alert(<span class="hljs-number">33</span>);
        divs[<span class="hljs-number">2</span>].detachEvent(<span class="hljs-string">&#x27;onclick&#x27;</span>, fn1);
    &#125;
&lt;/script&gt;</code></pre></div>

<p><strong>删除事件兼容性解决方案</strong></p>
<div class="hljs"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">removeEventListener</span>(<span class="hljs-params">element,eventName, fn</span>) </span>&#123;
    <span class="hljs-comment">// 判断当前浏览器是否支持 removeEventListener 方法</span>
    <span class="hljs-keyword">if</span> (element.removeEventListener) &#123;
        element.removeEventListener(eventName, fn);
    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (element.attacheEvent) &#123;
        element.detachEvent(<span class="hljs-string">&#x27;on&#x27;</span> + eventName, fn);
    &#125; <span class="hljs-keyword">else</span> &#123;
        element[<span class="hljs-string">&#x27;on&#x27;</span> + eventName] = <span class="hljs-literal">null</span>;
    &#125;
&#125;</code></pre></div>

<h2 id="DOM事件流"><a href="#DOM事件流" class="headerlink" title="DOM事件流"></a>DOM事件流</h2><blockquote>
<p>html中的标签都是相互嵌套的，我们可以将元素想象成一个盒子装一个盒子，document是最外面的大盒子。<br>当你单击一个div时，同时你也单击了div的父元素，甚至整个页面。</p>
<p>那么是先执行父元素的单击事件，还是先执行div的单击事件 ？？？</p>
</blockquote>
<p>事件流 描述的是从页面中接收事件的顺序。</p>
<p>事件发生时会在元素节点之间按照特定的顺序传播，这个过程即 DOM 事件流。</p>
<blockquote>
<p>比如：我们给页面中的一个div注册了单击事件，当你单击了div时，也就单击了body，单击了html，单击了document。</p>
</blockquote>
<p><img src="./1551166555833.png" srcset="/img/loading.gif" alt="1551166555833"></p>
<p><strong>DOM 事件流会经历3个阶段：</strong> </p>
<ol>
<li><p>捕获阶段</p>
</li>
<li><p>当前目标阶段</p>
</li>
<li><p>冒泡阶段 </p>
</li>
</ol>
<p>​    我们向水里面扔一块石头，首先它会有一个下降的过程，这个过程就可以理解为从最顶层向事件发生的最具体元素（目标点）的捕获过程；之后会产生泡泡，会在最低点（ 最具体元素）之后漂浮到水面上，这个过程相当于事件冒泡。 </p>
<p><img src="./1551169007768.png" srcset="/img/loading.gif" alt="1551169007768"></p>
<p><strong>注意：</strong></p>
<ol>
<li>JS 代码中只能执行捕获或者冒泡其中的一个阶段。</li>
<li>onclick 和 attachEvent 只能得到冒泡阶段</li>
<li>addEventListener(type, listener[,useCapture]) 如果 useCapture 是 true，表示在事件捕获阶段调用事件处理程序；如果是 flase（默认），表示在事件冒泡阶段调用事件处理程序。</li>
<li>有些事件是没有冒泡的，比如 onblur、onfocus、onmouseenter、onmouseleave</li>
</ol>
<h3 id="事件冒泡"><a href="#事件冒泡" class="headerlink" title="事件冒泡"></a><strong>事件冒泡</strong></h3><div class="hljs"><pre><code class="hljs js">  &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;father&quot;</span>&gt;
      &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;son&quot;</span>&gt;son盒子&lt;/div&gt;
  &lt;/div&gt;
  &lt;script&gt;
      <span class="hljs-comment">// onclick 和 attachEvent（ie） 在冒泡阶段触发</span>
      <span class="hljs-comment">// 冒泡阶段 如果addEventListener 第三个参数是 false 或者 省略 </span>
      <span class="hljs-comment">// son -&gt; father -&gt;body -&gt; html -&gt; document</span>
      <span class="hljs-keyword">var</span> son = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.son&#x27;</span>);
<span class="hljs-comment">// 给son注册单击事件</span>
      son.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;son&#x27;</span>);
      &#125;, <span class="hljs-literal">false</span>);
<span class="hljs-comment">// 给father注册单击事件</span>
      <span class="hljs-keyword">var</span> father = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.father&#x27;</span>);
      father.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;father&#x27;</span>);
      &#125;, <span class="hljs-literal">false</span>);
<span class="hljs-comment">// 给document注册单击事件，省略第3个参数</span>
      <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;document&#x27;</span>);
      &#125;)
  &lt;/script&gt;</code></pre></div>

<h3 id="事件捕获"><a href="#事件捕获" class="headerlink" title="事件捕获"></a><strong>事件捕获</strong></h3><div class="hljs"><pre><code class="hljs js">  &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;father&quot;</span>&gt;
      &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;son&quot;</span>&gt;son盒子&lt;/div&gt;
  &lt;/div&gt;
  &lt;script&gt;
      <span class="hljs-comment">// 如果addEventListener() 第三个参数是 true 那么在捕获阶段触发</span>
      <span class="hljs-comment">// document -&gt; html -&gt; body -&gt; father -&gt; son</span>
       <span class="hljs-keyword">var</span> son = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.son&#x27;</span>);
<span class="hljs-comment">// 给son注册单击事件，第3个参数为true</span>
       son.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
           alert(<span class="hljs-string">&#x27;son&#x27;</span>);
       &#125;, <span class="hljs-literal">true</span>);
       <span class="hljs-keyword">var</span> father = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.father&#x27;</span>);
<span class="hljs-comment">// 给father注册单击事件，第3个参数为true</span>
       father.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
           alert(<span class="hljs-string">&#x27;father&#x27;</span>);
       &#125;, <span class="hljs-literal">true</span>);
<span class="hljs-comment">// 给document注册单击事件，第3个参数为true</span>
      <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;document&#x27;</span>);
      &#125;, <span class="hljs-literal">true</span>)
  &lt;/script&gt;</code></pre></div>

<h2 id="事件对象"><a href="#事件对象" class="headerlink" title="事件对象"></a>事件对象</h2><h3 id="什么是事件对象"><a href="#什么是事件对象" class="headerlink" title="什么是事件对象"></a>什么是事件对象</h3><p>事件发生后，跟事件相关的一系列信息数据的集合都放到这个对象里面，这个对象就是事件对象。</p>
<p>比如：  </p>
<ol>
<li><p>谁绑定了这个事件。</p>
</li>
<li><p>鼠标触发事件的话，会得到鼠标的相关信息，如鼠标位置。</p>
</li>
<li><p>键盘触发事件的话，会得到键盘的相关信息，如按了哪个键。</p>
</li>
</ol>
<h3 id="事件对象的使用"><a href="#事件对象的使用" class="headerlink" title="事件对象的使用"></a>事件对象的使用</h3><p>事件触发发生时就会产生事件对象，并且系统会以实参的形式传给事件处理函数。</p>
<p>所以，在事件处理函数中声明1个形参用来接收事件对象。</p>
<div class="hljs"><pre><code class="hljs javascript">eventTarget.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>&#123;
    <span class="hljs-comment">// 这个 event 就是事件对象，还可以写成 e / evt</span>
&#125;
eventTarget.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>&#123;
     <span class="hljs-comment">// 这个 event 就是事件对象，还可以写成 e / evt</span>
&#125;)
eventTarget.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>,fn);
<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>&#123;
    <span class="hljs-comment">// 这个 event 就是事件对象，还可以写成 e / evt</span>
&#125;</code></pre></div>

<h3 id="事件对象的兼容性处理"><a href="#事件对象的兼容性处理" class="headerlink" title="事件对象的兼容性处理"></a>事件对象的兼容性处理</h3><p>事件对象本身的获取存在兼容问题：</p>
<ol>
<li><p>标准浏览器中是浏览器给方法传递的参数，只需要定义形参 e 就可以获取到。</p>
</li>
<li><p>在 IE6~8 中，浏览器不会给方法传递参数，如果需要的话，需要到 window.event 中获取查找。</p>
<p>解决：e = e || window.event;</p>
</li>
</ol>
<div class="hljs"><pre><code class="hljs ruby">只要“<span class="hljs-params">||</span>”前面为<span class="hljs-literal">false</span>, 不管“<span class="hljs-params">||</span>”后面是<span class="hljs-literal">true</span> 还是 <span class="hljs-literal">false</span>，都返回 “<span class="hljs-params">||</span>” 后面的值。
只要“<span class="hljs-params">||</span>”前面为<span class="hljs-literal">true</span>, 不管“<span class="hljs-params">||</span>”后面是<span class="hljs-literal">true</span> 还是 <span class="hljs-literal">false</span>，都返回 “<span class="hljs-params">||</span>” 前面的值。</code></pre></div>

<div class="hljs"><pre><code class="hljs js">&lt;div&gt;<span class="hljs-number">123</span>&lt;/div&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;div&#x27;</span>);
    div.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
            <span class="hljs-comment">// 事件对象</span>
            e = e || <span class="hljs-built_in">window</span>.event;
            <span class="hljs-built_in">console</span>.log(e);
    &#125;
&lt;/script&gt;</code></pre></div>

<h3 id="事件对象的属性和方法"><a href="#事件对象的属性和方法" class="headerlink" title="事件对象的属性和方法"></a>事件对象的属性和方法</h3><table>
<thead>
<tr>
<th>事件对象属性方法</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>e.target</td>
<td>返回触发事件的对象             标准</td>
</tr>
<tr>
<td>e.srcElement</td>
<td>返回触发事件的对象             非标准，IE6-8使用</td>
</tr>
<tr>
<td>e.type</td>
<td>返回事件的类型，比如 click、mouseover 等，不带on</td>
</tr>
<tr>
<td>e.cancelBubble</td>
<td>组织冒泡        非标准，IE6-8使用</td>
</tr>
<tr>
<td>e.returnValue</td>
<td>阻止默认事件（默认行为）非标准 IE6-8使用。比如不让链接跳转</td>
</tr>
<tr>
<td>e.preventDefaule()</td>
<td>阻止默认事件（默认行为）标准。比如不让链接跳转</td>
</tr>
<tr>
<td>e.stopPropagation()</td>
<td>阻止冒泡   标准</td>
</tr>
</tbody></table>
<h3 id="e-target-和-this-的区别"><a href="#e-target-和-this-的区别" class="headerlink" title="e.target 和 this 的区别"></a>e.target 和 this 的区别</h3><ul>
<li><p>this 是事件绑定的元素（绑定这个事件处理函数的元素） 。</p>
</li>
<li><p>e.target 是事件触发的元素。</p>
</li>
</ul>
<blockquote>
<div class="hljs"><pre><code class="hljs kotlin">常情况下terget 和 <span class="hljs-keyword">this</span>是一致的，
但有一种情况不同，那就是在事件冒泡时（父子元素有相同事件，单击子元素，父元素的事件处理函数也会被触发执行），
    这时候<span class="hljs-keyword">this</span>指向的是父元素，因为它是绑定事件的元素对象，
    而target指向的是子元素，因为他是触发事件的那个具体元素对象。</code></pre></div>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;div&gt;<span class="hljs-number">123</span>&lt;/div&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;div&#x27;</span>);
    div.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
        <span class="hljs-comment">// e.target 和 this指向的都是div</span>
        <span class="hljs-built_in">console</span>.log(e.target);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);

    &#125;);
&lt;/script&gt;</code></pre></div>

<p>事件冒泡下的e.target和this</p>
<div class="hljs"><pre><code class="hljs js">&lt;ul&gt;
    &lt;li&gt;abc&lt;/li&gt;
    &lt;li&gt;abc&lt;/li&gt;
    &lt;li&gt;abc&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    ul.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
          <span class="hljs-comment">// 我们给ul 绑定了事件  那么this 就指向ul  </span>
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// ul</span>

          <span class="hljs-comment">// e.target 触发了事件的对象 我们点击的是li e.target 指向的就是li</span>
          <span class="hljs-built_in">console</span>.log(e.target); <span class="hljs-comment">// li</span>
    &#125;);
&lt;/script&gt;</code></pre></div>

<h3 id="阻止默认行为"><a href="#阻止默认行为" class="headerlink" title="阻止默认行为"></a>阻止默认行为</h3><blockquote>
<p>html中一些标签有默认行为，例如a标签被单击后，默认会进行页面跳转。</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;a href=<span class="hljs-string">&quot;http://www.baidu.com&quot;</span>&gt;百度&lt;/a&gt;
&lt;script&gt;
    <span class="hljs-comment">// 2. 阻止默认行为 让链接不跳转 </span>
    <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;a&#x27;</span>);
    a.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
         e.preventDefault(); <span class="hljs-comment">//  dom 标准写法</span>
    &#125;);
    <span class="hljs-comment">// 3. 传统的注册方式</span>
    a.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
        <span class="hljs-comment">// 普通浏览器 e.preventDefault();  方法</span>
        e.preventDefault();
        <span class="hljs-comment">// 低版本浏览器 ie678  returnValue  属性</span>
        e.returnValue = <span class="hljs-literal">false</span>;
        <span class="hljs-comment">// 我们可以利用return false 也能阻止默认行为 没有兼容性问题</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    &#125;
&lt;/script&gt;</code></pre></div>

<h3 id="阻止事件冒泡"><a href="#阻止事件冒泡" class="headerlink" title="阻止事件冒泡"></a>阻止事件冒泡</h3><p>事件冒泡本身的特性，会带来的坏处，也会带来的好处。</p>
<blockquote>
<p>标准写法：利用事件对象里面的 stopPropagation() 方法</p>
<p>e.stopPropagation();</p>
<p>非标准写法：IE 6-8 利用事件对象 cancelBubble 属性</p>
<p>e.cancelBubble = true;</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">  &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;father&quot;</span>&gt;
      &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;son&quot;</span>&gt;son儿子&lt;/div&gt;
  &lt;/div&gt;
  &lt;script&gt;
      <span class="hljs-keyword">var</span> son = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.son&#x27;</span>);
<span class="hljs-comment">// 给son注册单击事件</span>
      son.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;son&#x27;</span>);
          e.stopPropagation(); <span class="hljs-comment">// stop 停止  Propagation 传播</span>
          <span class="hljs-built_in">window</span>.event.cancelBubble = <span class="hljs-literal">true</span>; <span class="hljs-comment">// 非标准 cancel 取消 bubble 泡泡</span>
      &#125;, <span class="hljs-literal">false</span>);

      <span class="hljs-keyword">var</span> father = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.father&#x27;</span>);
<span class="hljs-comment">// 给father注册单击事件</span>
      father.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;father&#x27;</span>);
      &#125;, <span class="hljs-literal">false</span>);
<span class="hljs-comment">// 给document注册单击事件</span>
      <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
          alert(<span class="hljs-string">&#x27;document&#x27;</span>);
      &#125;)
  &lt;/script&gt;</code></pre></div>

<p><strong>阻止事件冒泡的兼容性处理</strong></p>
<div class="hljs"><pre><code class="hljs javascript"><span class="hljs-keyword">if</span> (e &amp;&amp; e.stopPropagation) &#123;
    e.stopPropagation();
&#125; <span class="hljs-keyword">else</span> &#123;
    <span class="hljs-built_in">window</span>.event.cancelBubble = <span class="hljs-literal">true</span>;
&#125;</code></pre></div>

<h3 id="事件委托"><a href="#事件委托" class="headerlink" title="事件委托"></a>事件委托</h3><p>事件冒泡本身的特性，会带来的坏处，也会带来的好处。</p>
<h4 id="什么是事件委托"><a href="#什么是事件委托" class="headerlink" title="什么是事件委托"></a>什么是事件委托</h4><div class="hljs"><pre><code class="hljs plain">把事情委托给别人，代为处理。</code></pre></div>

<p>事件委托也称为事件代理，在 jQuery 里面称为事件委派。</p>
<blockquote>
<p>说白了就是，不给子元素注册事件，给父元素注册事件，把处理代码在父元素的事件中执行。</p>
</blockquote>
<p><strong>js事件中的代理：</strong></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>知否知否，应是弹窗在手<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>知否知否，应是弹窗在手<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>知否知否，应是弹窗在手<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>知否知否，应是弹窗在手<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>知否知否，应是弹窗在手<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span></code></pre></div>

<p>每点击 li 都会弹出对话框，给每个 li 注册事件是非常辛苦的，而且访问 DOM 的次数越多，这就会延长整个页面的交互就绪时间。</p>
<h4 id="事件委托的原理"><a href="#事件委托的原理" class="headerlink" title="事件委托的原理"></a>事件委托的原理</h4><p>​    给父元素注册事件，利用事件冒泡，当子元素的事件触发，会冒泡到父元素，然后去控制相应的子元素。</p>
<h4 id="事件委托的作用"><a href="#事件委托的作用" class="headerlink" title="事件委托的作用"></a>事件委托的作用</h4><ul>
<li><p>我们只操作了一次 DOM ，提高了程序的性能。</p>
</li>
<li><p>动态新创建的子元素，也拥有事件。</p>
</li>
</ul>
<div class="hljs"><pre><code class="hljs js">&lt;ul&gt;
    &lt;li&gt;知否知否，点我应有弹框在手！&lt;/li&gt;
    &lt;li&gt;知否知否，点我应有弹框在手！&lt;/li&gt;
    &lt;li&gt;知否知否，点我应有弹框在手！&lt;/li&gt;
    &lt;li&gt;知否知否，点我应有弹框在手！&lt;/li&gt;
    &lt;li&gt;知否知否，点我应有弹框在手！&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-comment">// 事件委托的核心原理：给父节点添加侦听器， 利用事件冒泡影响每一个子节点</span>
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    ul.addEventListener(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>&#123;
        <span class="hljs-comment">// e.target 这个可以得到我们点击的对象</span>
        e.target.style.backgroundColor = <span class="hljs-string">&#x27;pink&#x27;</span>;
    &#125;)
&lt;/script&gt;</code></pre></div>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/JavaScript/">JavaScript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JavaScript/">JavaScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/08/19/JS%20DOM%E6%93%8D%E4%BD%9C%E2%80%94%E2%80%94%E8%8A%82%E7%82%B9/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JS DOM操作——节点</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/08/17/JS%E7%9A%84%E5%BC%95%E7%94%A8%E2%80%94script/">
                        <span class="hidden-mobile">JS的引用-script</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">

  
	  <!-- 博客运营时间 -->
	  <div>
		  <span id="timeDate">载入天数...</span>
		  <span id="times">载入时分秒...</span>
		  <script>
		  var now = new Date();
		  function createtime(){
			  var grt= new Date("08/14/2020 00:00:00");//此处修改你的建站时间或者网站上线时间
			  now.setTime(now.getTime()+250);
			  days = (now - grt ) / 1000 / 60 / 60 / 24;
			  dnum = Math.floor(days);
			  hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
			  hnum = Math.floor(hours);
			  if(String(hnum).length ==1 ){
				  hnum = "0" + hnum;
			  }
			  minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
			  mnum = Math.floor(minutes);
			  if(String(mnum).length ==1 ){
						mnum = "0" + mnum;
			  }
			  seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
			  snum = Math.round(seconds);
			  if(String(snum).length ==1 ){
						snum = "0" + snum;
			  }
			  document.getElementById("timeDate").innerHTML = "本站安全运行&nbsp"+dnum+"&nbsp天";
			  document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
		  }
		  setInterval("createtime()",250);
		  </script>
		</div>
		
		
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


		

		
	
		<!-- 一言 -->
		<p id="hitokoto">:D 获取中...</p>
		<script>
		  fetch('https://v1.hitokoto.cn')
			.then(response => response.json())
			.then(data => {
			  const hitokoto = document.getElementById('hitokoto')
			  hitokoto.innerText = data.hitokoto
			  })
			  .catch(console.error)
		</script>
	</div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "JS DOM操作——事件&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>




















</body>
</html>
